package com.df.springmvc.system.manage.services;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.df.springmvc.supper.SupperServices;
import com.df.springmvc.system.manage.dao.InitDao;

/**
 * 本类只做数据运算处理
 * @author David
 */
@Service
public class InitServices extends SupperServices{
	@Autowired
	InitDao dao;
	
	public List<Object> queryFileTree(){
		ArrayList<Object> list=new ArrayList<Object>();
		list.add(new Object[]{"table","0","表"});
		list.add(new Object[]{"view","0","视图"});
		list.add(new Object[]{"proc","0","存储过程"});
		list.add(new Object[]{"func","0","函数"});
		list.add(new Object[]{"data","0","数据"});
		list.add(new Object[]{"other","0","其它"});
		for(String s:new String[]{"table","view","proc","func","data","other"}){
			List<Object> fileList=getFileList(s);
			for(Object filename:fileList){
				list.add(new Object[]{s + "#" + filename,s,("" + filename).replace(".sql","")});
			}
		}
		return list;
	}
	public List<Object> getFileList(String model){
		ArrayList<Object> list=new ArrayList<Object>();
		String sqlPath=webPath + "WEB-INF/sql/" + model;
		File f=new File(sqlPath);
		if(f.isDirectory()){
			for(File file:f.listFiles()){
				list.add(file.getName());
			}
		}
		return list;
	}
	public Object doView(HashMap<String,String> paramMap){
		// TODO Auto-generated method stub
		String model=paramMap.get("model");
		String id=paramMap.get("id");
		String sqlPath=webPath + "WEB-INF/sql/" + model + "/" + id;
		File file=new File(sqlPath);
		if(file.isFile() == false){
			return "";
		}
		StringBuffer sb=new StringBuffer();
		try{
			FileReader reader=new FileReader(file);
			BufferedReader br=new BufferedReader(reader);
			String t=br.readLine();
			while(t != null){
				sb.append(t + "\r\n");
				t=br.readLine();
			}
			try{
			}finally{
				br.close();
			}
		}catch(Exception e){
			// TODO: handle exception
			e.printStackTrace();
		}finally{
		}
		return sb.toString();
	}
	public Object deal(HashMap<String,String> paramMap) throws Exception{
		// TODO Auto-generated method stub
		String model=paramMap.get("model");
		String id=paramMap.get("id");
		String sqlPath=webPath + "WEB-INF/sql/" + model + "/" + id;
		File file=new File(sqlPath);
		if(file.isFile() == false){
			return "";
		}
		StringBuffer sb=new StringBuffer();
		try{
			FileReader reader=new FileReader(file);
			BufferedReader br=new BufferedReader(reader);
			String t=br.readLine();
			while(t != null){
				sb.append(t + "\r\n");
				t=br.readLine();
			}
			try{
			}finally{
				br.close();
			}
		}catch(Exception e){
			// TODO: handle exception
			e.printStackTrace();
		}finally{
		}
		Object rs=dao.deal(sb.toString());
		if("ok".equals(rs)){
		}else{
			return rs;
		}
		return "操作成功";
	}
}
